﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Security;
using Microsoft.VisualBasic;

namespace Meotom.Upload.v2.Data.Utilities
{
    public class Common
    {
        public static Common Instance
        {
            get { return new Common(); }
        }

        public string GetUploadByUser()
        {
            var uploadBy = string.Empty;
            var isAuthenticated = HttpContext.Current.User.Identity.IsAuthenticated;

            if (isAuthenticated)
            {
                var userDetail = Membership.GetUser(true);
                if (userDetail != null)
                    if (userDetail.ProviderUserKey != null)
                        uploadBy = userDetail.ProviderUserKey.ToString();
            }
            else
            {
                uploadBy = Instance.GetCookie("UpSSID");
                if (string.IsNullOrEmpty(uploadBy))
                {
                    var myGuid = Guid.NewGuid();
                    uploadBy = myGuid.ToString();
                }
            }
            return uploadBy;
        }

        public bool DeleteFile(string strPath)
        {
            try
            {
                var theFile = new FileInfo(strPath);
                if (theFile.Exists)
                {
                    File.Delete(strPath);
                }
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public string HexValue(int i)
        {
            return i.ToString("X");
        }

        public int IntValue(string hexValue)
        {
            return int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);
        }

        public void SetSession(string sessionName, string sessionValue)
        {
            HttpContext.Current.Session.Add(sessionName, sessionValue);

        }

        public string GetSession(string sessionName)
        {
            string sessionval;
            try
            {
                sessionval = HttpContext.Current.Session[sessionName].ToString();
            }
            catch (Exception)
            {
                sessionval = string.Empty;

            }
            return sessionval;
        }

        public void SetCookie(string cookieName, string cookieValue, DateTime expiresDate, string domain = "")
        {
            var httpCookie = HttpContext.Current.Response.Cookies[cookieName];
            if (httpCookie != null)
                httpCookie.Value = cookieValue;
            if (domain != null)
            {
                var cookie = HttpContext.Current.Response.Cookies[cookieName];
                if (cookie != null)
                    cookie.Domain = domain;
            }
            var httpCookie1 = HttpContext.Current.Response.Cookies[cookieName];
            if (httpCookie1 != null)
                httpCookie1.Expires = expiresDate;
        }

        public string GetCookie(string cookieName)
        {
            var cookieval = string.Empty;
            try
            {
                var httpCookie = HttpContext.Current.Request.Cookies[cookieName];
                if (httpCookie != null)
                    cookieval = httpCookie.Value;
            }
            catch (Exception)
            {
                cookieval = string.Empty;
            }
            return cookieval;
        }

        public ArrayList SplitString(string input)
        {
            var lst = new ArrayList();
            var str = input.Split(new[] {'-'});
            foreach (var s in str)
            {
                lst.Add(s);
            }
            return lst;
        }

        //public string FormatMultiline(string text)
        //{
        //    if (text == null)
        //    {
        //        return "";
        //    }
        //    var result = text;
        //    if (result.Length <= 0)
        //    {
        //        return text;
        //    }
        //    result = result.Replace(Constants.vbCr + Constants.vbLf, Constants.vbLf);
        //    result = result.Replace(Constants.vbCr, Constants.vbLf);
        //    result = result.Replace(Constants.vbLf, "<br />");
        //    return result;
        //}

        public string NoHtml(string html)
        {
            return html == string.Empty ? string.Empty : Regex.Replace(html, "<[^>]*>", string.Empty);
        }

        public string GetRfc822Date(DateTime dt)
        {
            var offSet = TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now).Hours;
            var tz = "+" + offSet.ToString().PadLeft(2, Convert.ToChar("0"));
            if (offSet < 0)
            {
                var i = offSet * -1;
                tz = "-" + i.ToString().PadLeft(2, Convert.ToChar("0"));
            }
            return dt.ToString("ddd, dd MMM yyyy HH:mm:ss " + tz.PadRight(5, Convert.ToChar("0")));
        }

        public string Utf8ToAscii(string strEncode)
        {
            var p2 = strEncode.Length;
            var p1 = 0;
            var oStr = "";
            while (p1 < p2)
            {
                switch (strEncode.Substring(p1, 1))
                {
                    case "â":
                    case "ầ":
                    case "ấ":
                    case "ậ":
                    case "ẩ":
                    case "ẫ":
                    case "ă":
                    case "ắ":
                    case "ặ":
                    case "ằ":
                    case "ẵ":
                    case "ẳ":
                    case "à":
                    case "ạ":
                    case "ả":
                    case "á":
                    case "ã":
                        oStr += "a";
                        break;
                    case "Â":
                    case "Ầ":
                    case "Ấ":
                    case "Ậ":
                    case "Ẩ":
                    case "Ẫ":
                    case "Ă":
                    case "Ắ":
                    case "Ặ":
                    case "Ằ":
                    case "Ẵ":
                    case "Ẳ":
                    case "À":
                    case "Ạ":
                    case "Ả":
                    case "Á":
                    case "Ã":
                        oStr += "A";
                        break;
                    case "ế":
                    case "ề":
                    case "ễ":
                    case "ể":
                    case "ệ":
                    case "è":
                    case "ẹ":
                    case "ẻ":
                    case "ẽ":
                    case "ê":
                    case "é":
                        oStr += "e";
                        break;
                    case "Ế":
                    case "Ề":
                    case "Ễ":
                    case "Ể":
                    case "Ệ":
                    case "Ê":
                    case "É":
                    case "È":
                    case "Ẹ":
                    case "Ẻ":
                    case "Ẽ":
                        oStr += "E";
                        break;
                    case "ồ":
                    case "ô":
                    case "ộ":
                    case "ó":
                    case "ổ":
                    case "ỏ":
                    case "ơ":
                    case "ở":
                    case "ợ":
                    case "ỡ":
                    case "õ":
                    case "ờ":
                    case "ớ":
                    case "ọ":
                    case "ố":
                    case "ò":
                    case "ỗ":
                        oStr += "o";
                        break;
                    case "Ồ":
                    case "Ô":
                    case "Ộ":
                    case "Ó":
                    case "Ổ":
                    case "Ỏ":
                    case "Ơ":
                    case "Ở":
                    case "Ợ":
                    case "Ỡ":
                    case "Õ":
                    case "Ờ":
                    case "Ớ":
                    case "Ọ":
                    case "Ố":
                    case "Ò":
                    case "Ỗ":
                        oStr += "O";
                        break;
                    case "ù":
                    case "ú":
                    case "ụ":
                    case "ủ":
                    case "ư":
                    case "ừ":
                    case "ứ":
                    case "ử":
                    case "ự":
                    case "ữ":
                    case "ũ":
                        oStr += "u";
                        break;
                    case "Ù":
                    case "Ú":
                    case "Ụ":
                    case "Ủ":
                    case "Ư":
                    case "Ừ":
                    case "Ứ":
                    case "Ử":
                    case "Ự":
                    case "Ữ":
                    case "Ũ":
                        oStr += "U";
                        break;
                    case "ỷ":
                    case "ỵ":
                    case "ỹ":
                    case "ý":
                    case "ỳ":
                        oStr += "y";
                        break;
                    case "Ỷ":
                    case "Ỵ":
                    case "Ỹ":
                    case "Ý":
                    case "Ỳ":
                        oStr += "Y";
                        break;
                    case "í":
                    case "ì":
                    case "ỉ":
                    case "ĩ":
                    case "ị":
                        oStr += "i";
                        break;
                    case "Í":
                    case "Ì":
                    case "Ỉ":
                    case "Ĩ":
                    case "Ị":
                        oStr += "I";
                        break;
                    case "Đ":
                        oStr += "D";
                        break;
                    case "đ":
                        oStr += "d";
                        break;
                    case "[":
                    case "]":
                    case "#":
                    case ":":
                    case "/":
                    case "\\":
                    case "?":
                    case ">":
                    case "<":
                    case "*":
                    case "^":
                    case "~":
                    case "%":
                    case "+":
                    case "(":
                    case ")":
                    case ",":
                    case ";":
                    case "!":
                    case "@":
                    case "'":
                        oStr += "";
                        break;
                    case ".":
                    case " ":
                    case "&":
                    case "\"":
                    case "=":
                    case "$":
                    case "--":
                        oStr += "-";
                        break;
                    default:
                        oStr += strEncode.Substring(p1, 1);
                        break;
                }
                p1 = p1 + 1;
            }
            return oStr;
        }

        public string BbCode(string strTextToReplace)
        {
            //'Regex for URL tag without anchor 

            var regExp = new Regex("\\[url\\]([^\\]]+)\\[\\/url\\]");
            strTextToReplace = regExp.Replace(strTextToReplace, "<a href=\"$1\">$1</a>");
            //'Regex for URL with anchor 

            regExp = new Regex("\\[url=([^\\]]+)\\]([^\\]]+)\\[\\/url\\]");
            strTextToReplace = regExp.Replace(strTextToReplace, "<a href=\"$1\">$2</a>");
            //'Image regex

            regExp = new Regex("\\[img\\]([^\\]]+)\\[\\/img\\]");
            strTextToReplace = regExp.Replace(strTextToReplace, "<img src=\"$1\" />");
            //Bold text

            regExp = new Regex("\\[b\\](.+?)\\[\\/b\\]");
            strTextToReplace = regExp.Replace(strTextToReplace, "<b>$1</b>");
            //'Italic text 

            regExp = new Regex("\\[i\\](.+?)\\[\\/i\\]");
            strTextToReplace = regExp.Replace(strTextToReplace, "<i>$1</i>");
            //'Underline text 

            regExp = new Regex("\\[u\\](.+?)\\[\\/u\\]");
            strTextToReplace = regExp.Replace(strTextToReplace, "<u>$1</u>");
            //'Font size

            regExp = new Regex("\\[size=([^\\]]+)\\]([^\\]]+)\\[\\/size\\]");
            strTextToReplace = regExp.Replace(strTextToReplace, "<span style=\"font-size: $1px\">$2</span>");
            //'Font color

            regExp = new Regex("\\[color=([^\\]]+)\\]([^\\]]+)\\[\\/color\\]");
            strTextToReplace = regExp.Replace(strTextToReplace, "<span style=\"color: $1\">$2</span>");
            return strTextToReplace;
        }

        public string DateTimeToNum()
        {
            return string.Format("{0:yyyy/MM/dd HH:mm:ss}", DateTime.Now).Replace(" ", "").Replace("/", "").Replace(
                ":", "");
        }

        public string Right(string strToCut, int length)
        {
            return strToCut.Substring(strToCut.Length - length, length);
        }

        public string Left(string strToCut, int length)
        {
            return strToCut.Substring(0, length);
        }
        public bool IsNumeric(string value)
        {
            double num;
            return double.TryParse(value.Trim(), out num);
        }

        public string SafeJson(string sIn)
        {
            var sbOut = new StringBuilder(sIn.Length);
            foreach (var ch in sIn)
            {
                if (Char.IsControl(ch) || ch == '\'')
                {
                    var ich = Strings.AscW(ch);
                    sbOut.Append("\\u" + ich.ToString("x4"));
                    continue;
                }
                if (ch == '"' || ch == '\\' || ch == '/')
                {
                    sbOut.Append('\\');
                }
                sbOut.Append(ch);
            }
            return sbOut.ToString();
        }
    }
}